<script>
var allocation_id = '{{.allocation_id}}';
var products_id = '{{.products_id}}';
var middle_id = '{{.middle_id}}';
var typeid = '{{.product.TypeId}}';
var _select_row = 0;
var _max_row = 0;
var defTr = [];
defTr.push('<tr id="addrow'+ _max_row +'" data-id="0">');
defTr.push('<td><input type="text" name="goods_name" /></td>');
defTr.push('<td></td>');
defTr.push('<td></td>');
defTr.push('<td></td>');
defTr.push('<td></td>');
defTr.push('<td></td>');
defTr.push('<td></td>');
defTr.push('<td></td>');
defTr.push('<td></td>');
defTr.push('<td></td>');
defTr.push('<td><input type="text" name="allocation_num" /></td>');
defTr.push('<td><span class="btn-tools" href="javascript:void(0);" onclick="deleteRow(this)"><i class="am-icon-trash-o am-text-danger"></i></span></td>');
defTr.push('</tr>');

$(function(){
    $("#dataTables").find('tbody').append(defTr.join(''));
    var enter_num = 0;

    if(typeid == 10 || typeid == 20 || typeid== 40) {
        $('#batchBivariatetable').show();
    } else {
        document.onkeydown = function (e) {
            if (!e) e = window.event;
            if ((e.keyCode || e.which) == 13) {

                if(e.target.name == 'goods_name') {  //在名称输入框回车
                    getInventory(e.target.value);
                }
                if(e.target.name == 'allocation_num') {  //在名称输入框回车
                    $("#dataTables").find('tbody').append(defTr.join(''));
                    $("#dataTables").find('tbody').find('[data-id="0"]').find('[name="goods_name"]').focus();
                }
                return false;
            }
        };
        $('#batchBivariatetable').hide();
    }
});

function deleteRow(obj) {
    $(obj).parent().parent().remove();
}

function getInventory(filter) {
    if(filter == '') {
        return false;
    }
    $.post('{{ urlfor "AllocationController.SelectErpInventory" }}?allocation_id='+allocation_id,JSON.stringify({'orFilter':filter, 'products_id': Number(products_id)}) ,function (res) {
        if(res.iTotalDisplayRecords == 0) {
            layer.msg("没有库存数据");
            return false;
        }
        if(res.iTotalDisplayRecords > 1) {  //需要弹窗选择
            popInventorys(filter);return false;
        } else {
            addGoods(res.aaData);return false;
        }
    });
}

function popInventorys(filter) {
    var uri = '{{ urlfor "AllocationController.PopSelectEntry" }}?query='+filter+'&product_id='+products_id;
    layer.open({
        type: 2,
        title: '选择库存',
        shadeClose: false,
        shade: 0.2,
        maxmin: false,
        shift: 1,
        area: ['1000px', '90%'],
        content: uri
    });
}
var addGoods = function(goods) {
    var t = $('#dataTables');
    $.each(goods ,function (idx, value) {
        var isset = t.find('tr[data-id="'+ value.Id +'"]').length;
        if(isset == 0) {
            var addtr = [];
            t.find('tr[data-id="0"]').remove();
            _max_row++;
            addtr.push('<tr id="addrow'+ _max_row +'" data-id="'+ value.Id +'">');
            addtr.push('<td style="display: none;"><input type="hidden" name="inventory_id" value="'+ value.Id +'" /> </td>');
            addtr.push('<td style="display: none;"><input type="hidden" name="snd_id" value="'+ value.Snd.id +'" /> </td>');
            addtr.push('<td style="display: none;"><input type="hidden" name="products_id" value="'+ value.Products.Id +'" /> </td>');
            addtr.push('<td><input type="text"  name="goods_name" readonly value="'+ productGroupName(value.Products) + '" /></td>');
            addtr.push('<td>'+ value.Snd.sph +'</td>');
            addtr.push('<td>'+ value.Snd.cyl +'</td>');
            addtr.push('<td>'+ value.Snd.add +'</td>');
            addtr.push('<td>'+ value.Snd.model +'</td>');
            addtr.push('<td>'+ value.Snd.color +'</td>');
            addtr.push('<td>'+ value.Acceptance.lot_number +'</td>');
            addtr.push('<td>'+ (value.Acceptance.manufacture_date > 0 ? timetransDate(value.Acceptance.manufacture_date) : '') +'</td>');
            addtr.push('<td>'+ (value.Acceptance.expiry_date > 0 ? timetransDate(value.Acceptance.expiry_date) : '') +'</td>');
            addtr.push('<td>'+ value.purchase_num +'</td>');
            addtr.push('<td><input type="text" name="allocation_num" value="'+ (value.allocation_num ? value.allocation_num : 1) +'" /></td>');
            addtr.push('<td><span class="btn-tools" href="javascript:void(0);" onclick="deleteRow(this)"><i class="am-icon-trash-o am-text-danger"></i></span></td>');
            addtr.push('</tr>');
            t.find('tbody').append(addtr.join(''));
            t.find('tbody > tr').last().find('[name="allocation_num"]').select();
        } else {
            layer.msg('已存在');
            t.find('tbody > tr').last().find('[name="goods_name"]').select();
        }
    });
};

//二维表添加
$('#batchBivariatetable').click(function(){
    var uri = '{{ urlfor "AllocationController.Bivariatetable" }}?product_id='+products_id;
    layer.open({
        type: 2,
        title: '二维表',
        shadeClose: false,
        shade: 0.2,
        maxmin: false,
        shift: 1,
        area: ['90%', '90%'],
        content: uri
    });
    return false;
});

function confirmBivariatetable(data) {
    $.post('{{ urlfor "AllocationController.SelectErpInventory" }}?allocation_id='+allocation_id,JSON.stringify({'query_dr':data.sph, 'query_am':data.cyl, 'products_id': Number(products_id)}) ,function (res) {
        if(res.iTotalDisplayRecords == 0) {
            layer.msg(data.sph +'/'+ data.cyl + " 没有库存数据");
            return false;
        }
        res.aaData[0].allocation_num = data.allocation_num;
        addGoods(res.aaData);return false;
    });
}

//获取中间表信息
function getMiddleData() {
    if(middle_id == '0') {
        return false;
    }
    $.post('{{  urlfor "AllocationController.GetMiddleDataForEntry"}}', {'middle_id':Number(middle_id)}, function(res){
        if(res.code == 0) {
            $.each(res.data, function(index, value){
                var goods = [];
                value.Inventory.Products = value.Products;
                value.Inventory.Snd = value.Snd;
                value.Inventory.allocation_num = value.AllocationNum;
                goods.push(value.Inventory);

                addGoods(goods);
            });

        }
    }, 'json');

}
getMiddleData();

$('#submit-details').click(function(){
    var tr = $('#dataTables').find('tbody tr');
    var _data = [];
    var isErr = false;
    $.each(tr ,function(index, value){
        var _this = $(this);
        var inventory_id = _this.find('[name="inventory_id"]').val();
        var products_id = _this.find('[name="products_id"]').val();
        var snd_id = _this.find('[name="snd_id"]').val();
        var allocation_num = _this.find('[name="allocation_num"]').val();
        if(inventory_id) {
            if(!allocation_num) {
                isErr = true;
                layer.alert("请填入调拨数量", function(i){
                    tr.eq(index).find('input[name="allocation_num"]').focus();
                    layer.close(i);
                });return false;
            }
            _data.push({'products_id':Number(products_id), 'middle_id':Number(middle_id),'inventory_id':Number(inventory_id), 'snd_id':Number(snd_id), 'allocation_num':Number(allocation_num),'allocation_id':Number(allocation_id)});
        }
    });
    if(isErr) {
        return false;
    }
    if(_data.length <= 0) {
        layer.alert("请选择需要调拨的商品");return false;
    }
    $.post('{{ urlfor "AllocationController.SubmitOrderData"}}', {'data':JSON.stringify(_data)}, function (res) {
        if(res.code == 1) {
            layer.alert(res.msg);return false;
        }
        parent.closeSelectComplete();
    });
});
</script>